package org.example.mq;

import lombok.extern.slf4j.Slf4j;
import org.example.model.CouponRecordMessage;
import org.example.service.CouponRecordService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.coupon_release_queue}")
public class CouponMQListener {

    @Autowired
    private CouponRecordService couponRecordService;

    @RabbitHandler
    public void releaseCouponRecord(CouponRecordMessage recordMessage, Message message, Channel channel) throws IOException {
        //1、获取tag
        long tag = message.getMessageProperties().getDeliveryTag();
        //2、消息消费是否成功的标识
        boolean flag = couponRecordService.releaseCouponRecord(recordMessage);
        try {
            //3、如果是成功消费，就确认消息消费成功
            if (flag) {
                channel.basicAck(tag, false);
            } else {
                //4、如果是失败消费，就重新进入队列
                log.error("释放优惠券失败flag=false,{}", recordMessage);
                channel.basicReject(tag, true);
            }
        } catch (IOException e) {
            log.error("释放优惠券记录异常:{},msg:{}", e, recordMessage);
            //5、释放优惠券记录出异常，重新进入队列
            channel.basicReject(tag, true);
        }
    }

    @RabbitHandler
    public void stringHandler(String msg, Message message, Channel channel) throws IOException {
        log.info(msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
    }


}
